// pages/homework/homework.js
const {
  imgConfig
} = require('../../utils/config.js')
const {
  config
} = require('../../utils/config.js')
var uploadFile = require('../../js/uploadImg/uploadImg.js');
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: `${imgConfig}`,
    statusBarHeight: app.globalData.statusBarHeight,
    isPopping: false, //是否已经弹出
    animPlus: {}, //旋转动画
    animCollect: {}, //item位移,透明度
    animTranspond: {}, //item位移,透明度
    animInput: {}, //item位移,透明度
    srcI: '',
    uploadRecord: '', //上传记录
    pageIndex: 1, //页码
    pageSize: 7, //页面数据大小
  },
  imgView(e){
    var list = []
    list.push(e.target.dataset.src)
    wx.previewImage({
      urls:list
    })
  },
  back: function () {
    wx.navigateBack({});
  },
  //按钮动画
  //点击弹出
  plus: function () {
    if (this.data.isPopping) {
      //缩回动画
      this.popp();
      this.setData({
        isPopping: false
      })
    } else if (!this.data.isPopping) {
      //弹出动画
      this.takeback();
      this.setData({
        isPopping: true
      })
    }
  },
  //调用聊天界面获取文件 文件类型限定为.rar/.zip 
  compress: function (e) {
    var that = this
    wx.chooseMessageFile({
      count: 1, //文件数
      type: 'file',
      success(res) {
        let tempFiles = res.tempFiles[0] //当前选中上传的文件
        console.log(tempFiles)
        const filePath = res.tempFiles[0].path //文件路径
        let size = res.tempFiles[0].size; //文件大小
        let fileName = res.tempFiles[0].name; //文件名
        // &&filename.indexOf(".xlsx") == -1
        if (fileName.indexOf(".rar") == -1 && fileName.indexOf(".zip") == -1) { //限制文件类型
          console.log('1111111111');
          wx.showModal({
            title: '提示',
            content: '文件类型必须为压缩包(.rar或.zip)!',
            confirmColor: '#0177ff',
            confirmText: '确定',
            success: function (res) {},
          })
        } else {
          //选取文件后添加文件描述
          wx.showModal({
            cancelColor: 'cancelColor',
            title: '提示',
            editable: true,
            placeholderText: '请添加文件描述',
            success(resp) {
              console.log(resp)
              if (resp.confirm) { //点击确定后
                //校验文件描述是否为空
                if (resp.content != "" && resp.content != undefined && resp.content != null) {
                  that.setData({ //将文件描述放入data中
                    fileRemark: resp.content
                  })
                } else { //文件描述为空
                  wx.showToast({
                    title: '文件描述不能为空!!!',
                    icon: "none",
                    duration: 1000
                  })
                  //结束方法
                  return
                }
                wx.showModal({
                  title: '提示',
                  content: '确定上传' + fileName + "?",
                  confirmColor: '#0177ff',
                  confirmText: '确定',
                  success: function (res) {
                    //点击确定还是取消
                    if (res.confirm) {
                      that.fileUpload(tempFiles, filePath, 0); //调用文件上传请求
                    }
                  }
                })
              } else if (resp.cancel) { //点击取消弹出提示
                wx.showToast({
                  title: '已取消',
                  icon: "none",
                  duration: 1000
                })
              }
            }
          })
        }
      }
    })
  },
  //从相册选取图片文件上传
  image: function (e) {
    var that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      camera: 'back',
      success: res => {
        console.log(res)
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '提示',
          editable: true,
          placeholderText: '请添加文件描述',
          success(resp) {
            console.log(resp)
            if (resp.confirm) {
              if (resp.content != "" && resp.content != undefined && resp.content != null) {
                that.setData({
                  fileRemark: resp.content
                })
              } else {
                wx.showToast({
                  title: '文件描述不能为空!!!',
                  icon: "none",
                  duration: 1000
                })
                return
              }
              that.fileUpload(res.tempFiles[0], res.tempFiles[0].tempFilePath, 1);
            } else if (resp.cancel) {
              wx.showToast({
                title: '已取消',
                icon: "none",
                duration: 1000
              })
            }
          }
        })
      }
    })
  },
  getCodeValue(e) {
    this.setData({
      code: e.detail.value,
    })
  },
  closeModal() {
    this.setData({
      show_input: false
    })
  },
  showCode() {
    this.setData({
      show_input: true
    })
  },
  //调用相机拍照上传
  camera: function (e) {
    var that = this
    //选择文件前
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      camera: 'back',
      success: res => {
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '提示',
          editable: true,
          placeholderText: '请添加文件描述',
          success(resp) {
            console.log(resp)
            if (resp.confirm) {
              if (resp.content != "" && resp.content != undefined && resp.content != null) {
                that.setData({
                  fileRemark: resp.content
                })
              } else {
                wx.showToast({
                  title: '文件描述不能为空!!!',
                  icon: "none",
                  duration: 1000
                })
                return
              }
              that.fileUpload(res.tempFiles[0], res.tempFiles[0].tempFilePath, 1);
            } else if (resp.cancel) {
              wx.showToast({
                title: '已取消',
                icon: "none",
                duration: 1000
              })
            }
          }
        })
      }
    })

  },
  /* 文件上传通用方法 
  file-文件对象
  filePath-文件路径
  type-文件类型 0-压缩包 1-图片
  */
  fileUpload(file, filePath, type) {
    var that = this
    //上传图片
    //你的域名下的/images/当前年月日文件下的/图片.png
    //图片路径可自行修改【(这二个参数就是你oss地址目录的下一个路径目录，比如:https://xxx.com/images/xxx.png)】
    uploadFile(filePath, 'codingmoreFile/',
  
      function (result) {
        var index = result.lastIndexOf("/")+1
        var fileName = result.substring(index,result.length)
        console.log(index,fileName)
        console.log("======上传成功====== 地址为：", result);
        wx.request({
          url: `${config}/wechat/wxHomework/uploadRecord`,
          data: {
            stuId: app.globalData.userInfo.id,
            fileName: (file.name == undefined ? fileName : file.name),
            filePath: result,
            fileType: type,
            fileRemark: that.data.fileRemark
          },
          success(res) {
            console.log(res)
            setTimeout(function () {
              wx.showModal({
                title: '提示',
                content: '上传成功!',
                showCancel: false
              })
              that.onLoad()
            }, 1100)
          }
        })
        //这个result就是返给你上传到oss上的地址链接
        wx.hideLoading();
      },
      function (result) {
        console.log("======上传失败======", result);
        setTimeout(function () {
          wx.showModal({
            title: '提示',
            content: '文件上传失败',
            showCancel: false
          });
          return;
        }, 1100)
        wx.hideLoading()
      }
    )
  },
  /* 文件上传通用方法 
  params-文件对象
  path-文件路径
  type-文件类型 0-压缩包 1-图片
  */
  upload: function (params, path, type) {
    var that = this
    wx.showToast({
      icon: "loading",
      title: "正在上传文件",
      duration: 1000
    })
    wx.uploadFile({
      url: `${config}/wechat/wxUpload/fileUpload`, //对应接口
      filePath: path,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        'file': params, //文件写入磁盘
        'stuId': app.globalData.userInfo.id, //记录存入数据库
        'name': (params.name == undefined ? "10" : params.name),
        'fileType': type,
        'fileRemark': that.data.fileRemark
      },
      success: function (res) {
        if (res.statusCode != 200) {
          setTimeout(function () {
            wx.showModal({
              title: '提示',
              content: '文件上传失败',
              showCancel: false
            });
            return;
          }, 1100)
        }
        let receivedata = JSON.parse(res.data);
        if (receivedata.msg == "success") {
          setTimeout(function () {
            wx.showModal({
              title: '提示',
              content: '上传成功!',
              showCancel: false
            })
            that.onLoad()
          }, 1100)
        }
      }
    })
  },
  //弹出动画
  popp: function () {
    //plus顺时针旋转
    var animationPlus = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationcollect = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationTranspond = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationInput = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    animationPlus.rotateZ(360).step(); //主按钮旋转角度
    animationcollect.translate(10, -30).rotateZ(360).opacity(1).step(); //相机按钮偏移量 旋转角度
    animationTranspond.translate(-45, -10).rotateZ(360).opacity(1).step(); //相册按钮偏移量 旋转角度
    animationInput.translate(-50, 50).rotateZ(360).opacity(1).step(); //压缩包按钮偏移量 旋转角度
    this.setData({
      animPlus: animationPlus.export(),
      animCollect: animationcollect.export(),
      animTranspond: animationTranspond.export(),
      animInput: animationInput.export(),
    })
  },
  //收回动画
  takeback: function () {
    //plus逆时针旋转
    var animationPlus = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationcollect = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationTranspond = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var animationInput = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    animationPlus.rotateZ(0).step();
    animationcollect.translate(0, 0).rotateZ(0).opacity(0).step();
    animationTranspond.translate(0, 0).rotateZ(0).opacity(0).step();
    animationInput.translate(0, 0).rotateZ(0).opacity(0).step();
    this.setData({
      animPlus: animationPlus.export(),
      animCollect: animationcollect.export(),
      animTranspond: animationTranspond.export(),
      animInput: animationInput.export(),
    })
  },
  //删除上传记录
  delRecord(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    wx.showModal({
      cancelColor: 'cancelColor',
      title: '提示',
      content: "确认要删除吗?",
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `${config}/wechat/wxHomework/delUploadRecord`,
            data: {
              id: id
            },
            success(res) {
              if (res.data.code == 0) {
                console.log('删除成功')
                wx.showToast({
                  title: '删除成功',
                  duration: 1000
                })
                that.onLoad()
              } else {
                wx.showToast({
                  title: '删除失败...',
                  icon: 'none',
                  duration: 1000
                })
                that.onLoad()
              }
            }
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '已取消',
            icon: "none",
            duration: 1000
          })
        }
      }
    })
  },
  /**
   * 获取作业提交记录
   */
  getFileUploadList() {
    var that = this
    wx.request({
      url: `${config}/wechat/wxHomework/getStuUploadRecord`,
      data: {
        page: that.data.pageIndex,
        limit: that.data.pageSize,
        stuId: app.globalData.userInfo.id
      },
      success(resp) {
        if (resp.data.code === 0) {
          that.setData({
            uploadRecord: resp.data.page.list
          })
        }
      }
    })
  },
  /**
   * 分页加载
   */
  pageLimit() {
    //上拉加载分页数据
    var that = this
    //存在提交记录 上拉执行  不存在不执行
    if (that.data.uploadRecord != "") {
      wx.showLoading({
        title: '玩命加载中',
        mask: true,
      })
      that.data.pageIndex++ //页码自增
      //发起请求
      wx.request({
        url: `${config}/wechat/wxHomework/getStuUploadRecord`,
        data: {
          page: that.data.pageIndex,
          limit: that.data.pageSize,
          stuId: app.globalData.userInfo.id
        },
        success(resp) {
          if (resp.data.code === 0) {
            that.setData({
              //拼接记录数据
              uploadRecord: that.data.uploadRecord.concat(resp.data.page.list)
            })
          }
          // 隐藏加载框
          wx.hideLoading();
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getFileUploadList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.pageLimit()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})